import 'package:route/route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo2/pages.dart';

import 'home/history_page.dart';
import 'home/home_page.dart';
import 'home/profile_page.dart';
import 'home/setting_page.dart';

class AppEntry extends StatefulWidget {
  const AppEntry({Key? key}) : super(key: key);

  @override
  State<AppEntry> createState() => AppEntryState();
}

class AppEntryState extends State<AppEntry> {
  int _currentIndex = 0;

  @override
  void initState() {
    router.onBottomNavigate = (String bottomBarPageName) {
      _routeBottomBar(bottomBarPageName);
    };
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: _navPages.map((e) => e.page).toList(growable: false),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        items: _navPages.map((e) => e.bottomNavigationBarItem).toList(),
        onTap: _changeIndex,
      ),
    );
  }

  void _changeIndex(int newIndex) {
    _currentIndex = newIndex;
    if (mounted) {
      setState(() {});
    }
  }

  final _navPages = [
    NavPages(
        const HomePage(),
        const BottomNavigationBarItem(
            icon: Icon(Icons.home), label: "home", backgroundColor: Colors.blue),
        FlutterPages.homePage),
    NavPages(
        const HistoryPage(),
        const BottomNavigationBarItem(
            icon: Icon(Icons.history), label: "history", backgroundColor: Colors.blue),
        FlutterPages.historyPage),
    NavPages(
        const SettingPage(),
        const BottomNavigationBarItem(
            icon: Icon(Icons.settings), label: "setting", backgroundColor: Colors.blue),
        FlutterPages.settingPage),
    NavPages(
        const ProfilePage(),
        const BottomNavigationBarItem(
            icon: Icon(Icons.person), label: "me", backgroundColor: Colors.blue),
        FlutterPages.mePage),
  ];

  void _routeBottomBar(String bottomBarName) {
    int index = _navPages.indexWhere((element) => bottomBarName == element.bottomBarName);
    if (-1 != index) {
      _changeIndex(index);
    }
  }
}

class NavPages {
  Widget page;
  BottomNavigationBarItem bottomNavigationBarItem;
  String bottomBarName;

  NavPages(this.page, this.bottomNavigationBarItem, this.bottomBarName);
}
